package com.spark.core;

import java.io.File;
import java.io.StringReader;

import org.apache.commons.io.FileUtils;

public class SparkTemplateLoader {
	
	private static SparkTemplateLoader instance = new SparkTemplateLoader();
	
	private SparkTemplateLoader(){}
	
	public static SparkTemplateLoader getInstance(){
		return instance;
	}
	
	@SuppressWarnings("unchecked")
	public SparkTemplate load(File file) throws Exception {
		String path = file.getAbsolutePath();
		SparkTemplate template = (SparkTemplate)CacheManager.getInstance().getSparkTemplate(path);
		if(template == null) {
			template = new SparkTemplate(file);
			String str = FileUtils.readFileToString(file, "UTF-8");
			XMap screen = parse(str);
			XMap actions = screen.getChild(SparkHandler.TAG_ACTIONS);
			template.setCache(screen.getBoolean(SparkTemplate.PROPERTITY_CACHE, false));
			template.setCheckSession(screen.getBoolean(SparkTemplate.PROPERTITY_CHECK_SESSION, true));
			template.setXML(str);
			if(actions != null)
			template.setActions(actions.getChilds());
			CacheManager.getInstance().setSparkTemplate(path, template);
		}
		return template;
	}
	
	protected XMap parse(String content) throws Exception {
		XMap m = XMapParser.parseReader(new StringReader(content), new SparkTemplateHandler());
		return m;
	} 
}
